package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"hh/cache"
	"hh/models"
	"strconv"
	"time"
)

type Ca struct {
	beego.Controller
}

func (c *Ca) List() {
	name := c.GetString("name")
	query := models.DB.Model(&models.As{})
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	offset := (page - 1) * size
	var count int64
	query.Count(&count)
	up := page - 1
	if up < 1 {
		up = page
	}
	var ca []models.As
	query.Limit(size).Offset(offset).Find(&ca)
	key := "user_list"
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res != "" {
		json.Unmarshal([]byte(res), &ca)
	} else {

		jsonData, _ := json.Marshal(&ca)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*3)
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: ca,
	}
	c.ServeJSON()

}
func (c *Ca) Show() {
	id, _ := c.GetInt("id")
	var ca []models.As
	key := "user_show" + strconv.Itoa(id)
	models.DB.Where("id = ?", id).Find(&ca)
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res != "" {
		json.Unmarshal([]byte(res), &ca)
	} else {

		jsonData, _ := json.Marshal(&ca)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*66)
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: ca,
	}
	c.ServeJSON()
}
